//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package bulletin_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type _BulletinRecycleDao struct {
	mc *mongo.Collection
}

func newBulletinRecycleDao(db *mongo.Database) (*_BulletinRecycleDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_BULLETIN + "info_recycle")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_BulletinRecycleDao{mc: mc}, nil
}

func (db *_BulletinRecycleDao) Insert(ctx context.Context, dbItem *BulletinInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_BulletinRecycleDao) Get(ctx context.Context, bulletinId, projectId string) (*BulletinInfoDbItem, error) {
	retItem := &BulletinInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": bulletinId, "projectId": projectId}).Decode(retItem)
	return retItem, err
}

func (db *_BulletinRecycleDao) Remove(ctx context.Context, bulletinId, projectId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": bulletinId, "projectId": projectId})
	return err
}

func (db *_BulletinRecycleDao) ListById(ctx context.Context, projectId string, bulletinIdList []string) ([]*BulletinInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": bulletinIdList}, "projectId": projectId})
	if err != nil {
		return nil, err
	}
	retList := []*BulletinInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_BulletinRecycleDao) DistinctBulletIdByProject(ctx context.Context, projectId string) ([]string, error) {
	itemList, err := db.mc.Distinct(ctx, "_id", bson.M{"projectId": projectId})
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, item := range itemList {
		retList = append(retList, item.(string))
	}
	return retList, nil
}
